﻿using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Casamiel.Common;
using MediatR;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Casamiel.Application.Commands
{
    /// <summary>
    /// Check permission command handler.
    /// </summary>
    public sealed class CheckPermissionCommandHandler : BaseCommandHandler, IRequestHandler<CheckPermissionCommand, bool>
    {

        /// <summary>
        /// Initializes a new instance of the
        /// </summary>
        /// <param name="httpClientFactory">Http client factory.</param>
        public CheckPermissionCommandHandler(INetICService netICService, IHttpClientFactory httpClientFactory, IOptionsSnapshot<CasamielSettings> optionsSnapshot)
       : base(netICService, httpClientFactory, optionsSnapshot)
        {

        }
        /// <summary>
        /// Handle the specified request and cancellationToken.
        /// </summary>
        /// <returns>The handle.</returns>
        /// <param name="request">Request.</param>
        /// <param name="cancellationToken">Cancellation token.</param>
        public async Task<bool> Handle(CheckPermissionCommand request, CancellationToken cancellationToken)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }
            var url = "v1/Account/CheckPermission";

            var data = new { pid = request.Pid, token = request.Token };

            var result = await PostAsync(url, JsonConvert.SerializeObject(data), "newstoreApi").ConfigureAwait(false);
            var dynamicdata = JsonConvert.DeserializeObject<JObject>(result);
            if (dynamicdata["resultNo"].ToString() == "00000000")
            {
                return true;
            }
            return false;

        }

        //private async Task<string> PostAsync(string url, string data)
        //{
        //    var requestMessage = new HttpRequestMessage(HttpMethod.Post, url);
        //    requestMessage.Content = new StringContent(data, System.Text.Encoding.UTF8, "application/json");

        //    var client = _clientFactory.CreateClient("newstoreApi");
        //    var response = await client.SendAsync(requestMessage);
        //    if (response.IsSuccessStatusCode)
        //    {
        //        var result = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
        //        return result;
        //    }
        //    throw new HttpRequestException();
        //}
    }
}
